layui.use(['layer', 'form', 'formX', 'setter', 'mynotice', 'admin', 'util', 'notice', 'ax'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var setter = layui.setter;
    var mynotice = layui.mynotice;
    var admin = layui.admin;
    var util = layui.util;
    var $ax = layui.ax;
    
    var uuid = guid();
    var cosprogress = 0;
    var cover = 'https://sxp-1259003793.cos.ap-chongqing.myqcloud.com/images/6ec6ed77ec1b4c3db977e326c744f2fa.jpg';
    var videoId = '';
    var autosavePrefix = $('#mpuserid').val() + '-upmp';
    
    tinymce.init({
    	selector: '#editor_id',
    	language: 'zh_CN',
    	placeholder: '请输入正文',
    	height: 550, // 高度
    	min_height: 550,
    	resize: false, // 禁止拉伸
    	statusbar: false, //底部状态栏
    	convert_urls: false, // 上传图片关闭自动转为相对路径
    	style_formats_autohide: true, // 隐藏当前不可用的样式列表
    	cache_suffix: '?v=5.0.4', // 缓存请求后缀
    	menubar: false, // 禁用菜单栏
    	contextmenu: '',
    	icons: 'sxp',
        plugins: [
    		" autolink lists link image charmap print preview anchor emoticons lineheight codesample",
    		"searchreplace visualblocks code autoresize axupimgs indent2em autosave hr",
    		"insertdatetime media table contextmenu paste imagetools wordcount",
    		"code"
    	],
    	toolbar: "undo redo removeformat bold italic blockquote bullist numlist strikethrough hr underline codesample alignleft aligncenter alignright alignjustify outdent indent indent2em image media link unlink table charmap emoticons forecolor backcolor",
    	autosave_interval: '5s',
    	autosave_retention: '720m',
    	autosave_restore_when_empty: true,
    	autosave_prefix: autosavePrefix,
    	automatic_uploads: true,
    	autosave_ask_before_unload: false, // 当关闭或跳转URL时，弹出提示框提醒用户仍未保存变更内容。默认开启提示
    	setup: function(editor) {
			admin.showLoading('#editor-loading', 4, '.8');
    	},
    	init_instance_callback : function(editor) {
        	admin.removeLoading('#editor-loading', true, false);
        	$('#editor_id').removeClass('layui-hide');
        	layui.form.render();
    	},
    	images_upload_handler: function (blobInfo, succFun, failFun) {
        	var xhr, formData;
        	var file = blobInfo.blob();//转化为易于理解的file对象
        	var size = 5 * 1024 * 1024;
			if(file.size > size){
				failFun('文件不能超过5M');
				return;
			}
        	xhr = new XMLHttpRequest();
        	xhr.withCredentials = false;
        	xhr.open('POST', '/common/tinyimg?uuid=' + guid());
        	xhr.onload = function() {
        		var json;
        		if (xhr.status != 200) {
            		if(xhr.status === 503){
        				failFun('请求失败，请稍后再试');
        				return;
        			}else if(xhr.status === 401){
        				setter.removeToken();
                		location.replace('/login');
                		return;
        			}
        			if(xhr.responseJSON !== undefined){
    					failFun(data.responseJSON.msg);
        				return;
        			}else{
        				failFun('请求失败，请稍后再试');
        				return;
        			}
        			failFun('请求失败，请稍后再试');
        			return;
        		}
        		json = JSON.parse(xhr.responseText);
	        	if(json.code != 0){
	        		failFun(json.msg);
	        		return;		
	        	}
	        	succFun(json.data);
        	};
        	formData = new FormData();
        	formData.append('uploadFile', file, file.name );
        	xhr.send(formData);
    	},
    	file_picker_callback: function (callback, value, meta) {
            // 文件分类
            var filetype = '.jpg, .jpeg, .png, .gif, .mp3, .mp4';
            // 后端接收上传文件的地址
            var upurl = '/common/tinyimg';
            var uploadType = 0;
            // 为不同插件指定文件类型及后端地址
            switch(meta.filetype){
                case 'image':
                    filetype = '.jpg, .jpeg, .png, .gif';
                    upurl = '/common/tinyimg';
                    break;
                case 'media':
                    filetype = '.mp3, .mp4';
                    upurl = '/common/video';
                    uploadType = 1;
                    break;
                case 'file':
                default:
            }
            // 模拟出一个input用于添加本地文件
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', filetype);
            input.click();
            input.onchange = function() {
            	var file = this.files[0];
                var form = new FormData();
                form.append("uploadFile", file); 
				if(meta.filetype == 'media'){
					var size = 200 * 1024 * 1024;
	    			if(file.size > size){
	    				mynotice.error('文件不能超过200M');
	    				return;
	    			}
	    			var contenthtml = tinymce.get('editor_id').getContent();
	    			console.log(contenthtml);
	    			if(contenthtml && contenthtml.indexOf('<video') != -1){
		    			mynotice.error('只能上传一个视频');
	    				return;
	    			}
				}else{
					var size = 5 * 1024 * 1024;
	    			if(file.size > size){
	    				mynotice.error('文件不能超过5M');
	    				return;
	    			}
				}
				uuid = guid()
    			var loaderIndex = admin.open({
    				type: 1,
    				title: ['上传进度', 'font-size:18px;color: #303133;border-bottom: 0px solid #f1f1f1;background-color:#fff;'],
    				content: '<div id="loader" style="margin-top: 20px;"><progress id="progress" value="0" max="100"></progress><output for="p">0</output></div>',
    				closeBtn: 0,
    				offset: 'auto',
    				area: ['500px', '200px'],
    				success: function(layero, dIndex){
    					const _PRG = document.getElementById('progress'),
    					_OUT = document.querySelector('[for=p]'),
    					K = 1,TMAX = K * _PRG.max;
    					function load(t = 0) {
    						if(cosprogress >= 100){
    							return;
    						}
    						if (t <= TMAX) {
    							if (t % K === 0) _OUT.value = _PRG.value = t / K;
        						var _that = this;
        						setTimeout(function(){
    					    		var ajax = new $ax('/cosprogress?uuid=' + uuid, 'post', function (res) {
    					    			cosprogress = res.data;
    					    			requestAnimationFrame(load.bind(this, res.data));
    					    	    }, function (res) {
    					    	    	console.log('------获取进度失败-----' + res.msg);
    					    	    });
    					        	ajax.start();
    					    	},1000);
    					  }
    					};
    					load();
    				}
    			});
    			
    			$.ajax({
    	            	url: upurl + "?uuid=" + uuid,
    	                type: "post",
    	                data: form,
    					cache: false, // 上传文件无需缓存
    	                processData: false, // 用于对data参数进行序列化处理 这里必须false
    	                contentType: false, // 必须
				    	beforeSend: function (data) {
				        	var token = setter.getToken();
				        	if(token){
				        		data.setRequestHeader('Authorization', 'Bearer ' + token);
				        	}
				        },
    	                success: function(data) {
    						if(data.code == 0){
    							layer.close(loaderIndex);
    							console.log(data);
    							if(uploadType == 1){
    								callback(data.data.videoUrl);
    								cover = data.data.coverUrl;
    								videoId = data.data.videoId;
    							}else{
    								callback(data.data);
    							}
	    				 		mynotice.success('上传成功');
    						}else{
    							layer.close(loaderIndex);
    							mynotice.error(data.msg);
    						}
    	                },
    	                error: function(data) {
	    					layer.closeAll('loading');
				        	var res = {};
				        	res['code'] = data.status;
				        	res['data'] = null;
				        	if(data.status === 503){
				        		res['msg'] = '请求失败，请稍后再试';
				        	}else if(data.status === 401){
				        		setter.removeToken();
				                location.replace('/login');
				        	}
				        	if(data.responseJSON !== undefined){
			        			res['msg'] = data.responseJSON.msg;
			            	}else{
			            		res['msg'] = "请求失败，请稍后再试";
			            	}
			        		mynotice.error(res.msg);
	    	             }
    	           });
    			$('#loader').removeClass('layui-hide');
            };
        },
        
        video_template_callback: function(data) {
        	return '<div id="v_'+ videoId +'"><video id="'+ videoId +'" poster="'+ cover +'" controls="controls" width="'+ data.width +'" height="'+ data.height +'">'+
        			'<source src="'+ data.source +'" type="'+ data.sourcemime +'" />'+
        		'</video></div>';
        }

    });
    
    function guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}
	
	var mp = {
    	publishEdit: (data) => { // 更新资源
    		// 获取富文本内容
        	var content = tinymce.get('editor_id').getContent();
    	    // 获取富文本纯文本
    	    var contentText = tinymce.get('editor_id').getContent({format: 'text'});
    	    if(admin.util.fullTextIsEmpty(content)){
    	    	mynotice.errorc('正文不能为空');
    	    	return false;
    	    }
    	    data.field.content = content;
    	    data.field.contentText = contentText;
    	    if($("#userlabel").tagsinput('items') != ''){
        		data.field.tags = $("#userlabel").tagsinput('items');
        	}
    	    var columnId = data.field.columnId;
    	    var cityCode = data.field.cityCode;
    	    if(cityCode){
	    		var arrcode = cityCode.split(',');
    	    	$.each(arrcode, (i, v) => {
    	    		if(i == 0){
    	    			data.field.province = v;
    	    		}else if(i == 1){
    	    			data.field.city = v;
    	    		}else if(i == 2){
    	    			data.field.county = v;
    	    		}
    	    	})
	    	}
	    	if(data.field.draft == '1'){
	    		mynotice.load('正在保存，请稍后...');
	    	}else{
	    		mynotice.load('正在发布，请稍后...');
	    	}
    	    var ajax = new $ax('/api/zp/update', 'post', function (res) {
    	    	mynotice.destroy();
    	    	if(data.field.draft == '0'){
    	    		$("#resEditForm")[0].reset();
	                layui.form.render();
	    	    	window.localStorage.removeItem(autosavePrefix + 'draft');
	    	    	window.localStorage.removeItem(autosavePrefix + 'time');
	    	    	$('body').html(res.data);
    	    	}else if(data.field.draft == '1'){
    	    		mynotice.success('保存成功');
    	    	}else {
    	    		mynotice.success('提交成功');
    	    		setTimeout(function(){
						window.location.href = "/res/manage/list";
					},600);
    	    	}
    	    }, function (res) {
    	    	mynotice.destroy();
    	    	mynotice.error(res.msg);
    	    });
    	    ajax.setData(JSON.stringify(data.field));
    	    ajax.start();
    	},
	}
    
    /*更新*/
    form.on('submit(publishEditArticle)', function(data){
    	data.field.draft = "0"
    	mp.publishEdit(data);
	    return false;
    });
    
    /*立即发布*/
    form.on('submit(publishNowEditArticle)', function(data){
    	data.field.draft = "0"
    	mp.publishEdit(data);
	    return false;
    });
    
    /*存草稿*/
    form.on('submit(draftEditArticle)', function(data){
    	data.field.draft = "1"
    	mp.publishEdit(data);
	    return false;
    });
    
    var m = new Map();
  	var tims = [];
  	var ms = {};
	// 两个小时后
	var now = new Date();
	var time = now.getTime() + 2 * 60 * 60 * 1000;
	var after = new Date(time)
  	ms['hs'] = getarryh(after.getHours(), 24);
  	ms['ms'] = getarryh(after.getMinutes(), 60);
	m.set(util.toDateString(after, 'yyyy-MM-dd'), ms);
	var kjs = {};
	kjs['key'] = util.toDateString(after, 'yyyy-MM-dd');
	kjs['value'] = util.toDateString(after, 'MM月dd日')
	tims.push(kjs);
	// 后七天 
	var ks = {};
    ks['hs'] = getarry(24);
	ks['ms'] = getarry(60);
	for (let i = 1; i < 8; i++) {
	    const time = new Date(new Date().setDate((after.getDate() + i)));
	    var dates = {};
	    dates['key'] = util.toDateString(time, 'yyyy-MM-dd');
	    dates['value'] = util.toDateString(time, 'MM月dd日');
	    m.set(util.toDateString(time, 'yyyy-MM-dd'), ks); 
	    tims.push(dates);
	}
	
	function getarry(n) {
		var arr = [];
		for (let i = 0; i < n; i++) {
		    arr.push(i)
		}
		return arr;
	}
	
	function getarryh(s, n) {
		var arr = [];
		for (let i = s; i < n; i++) {
		    arr.push(i)
		}
		return arr;
	}
	
	util.event('lay-event', {
		timingArticle: function(){
			admin.open({
                    type: 1,
                    area: '600px',
                    offset: '100px',
                    move: false,
                    shadeClose: true,
                    shade: 0.6,
                    title: ['定时发布', 'color:#444444'],
                    content: $('#timingTimeId').html(),
                    success: function (layero, dIndex) {
	                    var dwarr = tims[0].key.split('-');
						var mvww = m.get(tims[0].key);
						var hsd = '0' + mvww.hs[0];
						var msd = '0' + mvww.ms[0];
	                    $('#timingId').text(dwarr[0] + ' 年' + dwarr[1] + ' 月' + dwarr[2] + ' 日 ' + hsd.slice(-2) + ':' + msd.slice(-2));
                    	var yh = '';
                    	$.each(tims, (i, v) => {
                    		if(i == 0){
                    			var ht = '';
                    			var mt = '';
                    			var ttim = $('#ttim').val();
                    			var mv = {};
                    			if(ttim){
                    				var dkv = util.toDateString(ttim, 'yyyy-MM-dd')
                    				mv = m.get(dkv);
                    			}else{
                    				var mv = m.get(v.key);
                    			}
                    			$.each(mv.hs, (i, v2) => {
                    				 ht += '<option value="' + v2 + '">' + v2 + '</option>';
                    			})
                    			$.each(mv.ms, (i, v3) => {
                    				 mt += '<option value="' + v3 + '">' + v3 + '</option>';
                    			})
                    			$('#hourId').html(ht);
                    			$('#minuteId').html(mt);
                    		}
                    		yh += '<option value="' + v.key + '">' + v.value + '</option>';
                    	})
                    	$('#dateId').html(yh);
                    	form.render('select');
                    	
                    	form.on('select(datefilter)', function(data){
                    		var ht = '';
                    		var mt = '';
						  	var mv = m.get(data.value);
						  	var hv = $('#hourId').val();
						  	var mvs = $('#minuteId').val();
                			$.each(mv.hs, (i, v2) => {
                				ht += '<option value="' + v2 + '">' + v2 + '</option>';
                			})
                			$.each(mv.ms, (i, v3) => {
                				mt += '<option value="' + v3 + '">' + v3 + '</option>';
                			})
                			$('#hourId').html(ht);
                    		$('#minuteId').html(mt);
                			form.render('select');
                			form.val("timingEditForm", {
							  "hour": hv,
							  "minute": mvs,
							});
							hv = '0' + hv;
							mvs = '0' + mvs;
							var darr = data.value.split('-');
							$('#timingId').text(darr[0] + ' 年' + darr[1] + ' 月' + darr[2] + ' 日 ' + hv.slice(-2) + ':' + mvs.slice(-2));
						});
						
						form.on('select(hourfilter)', function(data){
							var darr = $('#dateId').val().split('-');
							var hv = '0' + data.value;
							var mvs = '0' + $('#minuteId').val();
							$('#timingId').text(darr[0] + ' 年' + darr[1] + ' 月' + darr[2] + ' 日 ' + hv.slice(-2) + ':' + mvs.slice(-2));
						});
						
						form.on('select(minutefilter)', function(data){
							var darr = $('#dateId').val().split('-');
							var hv = '0' + $('#hourId').val();
							var mvs = '0' + data.value;
							$('#timingId').text(darr[0] + ' 年' + darr[1] + ' 月' + darr[2] + ' 日 ' + hv.slice(-2) + ':' + mvs.slice(-2));
						});
                    	
                     	// 表单提交事件
                        form.on('submit(timingPublishSubmit)', function (data) {
                        	$.fn.serializeObject = function() {
							   var o = {};
							   var a = this.serializeArray();
							   $.each(a, function() {
							       if (o[this.name] !== undefined) {
							           if (!o[this.name].push) {
							               o[this.name] = [o[this.name]];
							           }
							           o[this.name].push(this.value || '');
							       } else {
							           o[this.name] = this.value || '';
							       }
							   });
							   return o;
							};
                        	var formData = $("#resEditForm").serializeObject();
                        	var hds = '0' + data.field.hour;
                        	var mds = '0' + data.field.minute;
                        	var timingTime = data.field.date + ' ' + hds.slice(-2) + ":" + mds.slice(-2)
                        	formData['timingTime'] = timingTime; // '2020-07-30 13:48'
                        	console.log(JSON.stringify(formData));
				    	    
				    	    // 获取富文本内容
				        	var content = tinymce.get('editor_id').getContent();
				    	    // 获取富文本纯文本
				    	    var contentText = tinymce.get('editor_id').getContent({format: 'text'});
				    	    if(admin.util.fullTextIsEmpty(content)){
				    	    	mynotice.errorc('正文不能为空');
				    	    	return false;
				    	    }
				    	    formData['content'] = content;
				    	    formData['contentText'] = contentText;
				    	    if($("#userlabel").tagsinput('items') != ''){
				        		data.field.tags = $("#userlabel").tagsinput('items');
				        	}
				    	    var columnId = formData.columnId;
				    	    var cityCode = formData.cityCode;
				    	 
					    	if(cityCode){
					    		var arrcode = cityCode.split(',');
				    	    	$.each(arrcode, (i, v) => {
				    	    		if(i == 0){
				    	    			formData['province'] = v;
				    	    		}else if(i == 1){
				    	    			formData['city'] = v;
				    	    		}else if(i == 2){
				    	    			formData['county'] = v;
				    	    		}
				    	    	})
					    	}
				    	    mynotice.load('正在发布，请稍后...');
				    	    var ajax = new $ax('/api/zp/regularReleaseEdit', 'post', function (res) {
				    	    	mynotice.destroy();
				    	    	$("#resEditForm")[0].reset();
                    			layui.form.render();
				    	    	window.localStorage.removeItem(autosavePrefix + 'draft');
			    	    		window.localStorage.removeItem(autosavePrefix + 'time');
			    	    		mynotice.success('发布成功');
			    	    		setTimeout(function(){
									window.location.href = "/res/manage/list";
								},600);
				    	    }, function (res) {
				    	    	mynotice.destroy();
				    	    	mynotice.error(res.msg);
				    	    });
				    	    ajax.setData(JSON.stringify(formData));
				    	    ajax.start();
                            return false;
                        });
                        // 禁止弹窗出现滚动条
                        $(layero).children('.layui-layer-content').css('overflow', 'visible');
						$('html').css("overflow", "hidden");
                    },
                    end: function(){
						$('html').css("overflow", "");
                    }
                });
		},
		bodyload: function(){ // 切换体载
			window.location.href="/profile_v2/" + $(this).data('key');
		},
		usersettings: function(){ // 设置
			window.location.href="/u/usersettings";
		},
		managelist: function(){
			window.location.href="/res/manage2/list";
		}
	})
    
    
});